<?php
namespace Wang\Database;
use PDO;

/**
*  数据操作类
**/
class DbPdo implements Database{

	private $db;//数据库实例对象

	static $_instance;//单例

	protected $_handle;//查询句柄

	private function __construct($db = array()){
		try{
			$dsn = 'mysql:host='.$db['host'].':'.$db['port'].';dbname='.$db['dbname'].'';
			$username = $db['username'];
			$password = $db['password'];
			$options = array(
			    PDO::MYSQL_ATTR_INIT_COMMAND => $db['charset'],
			); 

			$this->db = new PDO($dsn, $username, $password, $options);
		}catch(Exception $e){
			throw new Exception($e->getMessage());
		}
	}

	function query($sql){
		$this->_handle = $this->db->query($sql);
		return $this;

	}

	/**
	 * 获取结果集
	 * @return array
	 */
	function fetchAll(){
		$data = $this->_handle->fetchAll();
		return $data;
	}

	/**
	 * 返回受 DELETE、INSERT、 或 UPDATE 语句影响的行数
	 * @return int 返回受影响的行数
	 */
	function affectRows(){
		$count = $this->_handle->rowCount();
		return $count;
	}

	/**
	 * @return array 获取一行数据
	 */
	function fetchRow(){
		$data = $this->_handle->fetchAll();
		return $data[0];
	}
	/**
	 * 获取实例
	 */

	static function getInstance($config){
		if(!self::$_instance){
			self::$_instance = new self($config);
		}
		return self::$_instance;
	}
}